The basename Command
The basename
command extracts the filename from a path.
How to use the basename command
The basename
command takes a single argument, which is the path to the file or directory whose filename you want to extract. It returns the filename, minus the directory path.
For example, to extract the filename from the following path:
/home/user/myfile.txt
You would type the following command:
basename /home/user/myfile.txt
The output of the command would be:
myfile.txt
basename command options
-s suffix
: Removes the specified suffix from the filename. For example, to remove the .txt suffix from the filename myfile.txt, you would type the following command:
basename myfile.txt -s .txt
The output of the command would be:
myfile
-a
: Removes all suffixes from the filename. For example, to remove all suffixes from the filename myfile.txt.gz, you would type the following command:
basename myfile.txt.gz -a
The output of the command would be:
myfile
basename command examples
Here are some examples of how to use the basename
command:
To extract the filename from a URL:
basename https://example.com/myfile.txt
Output:
myfile.txt
To remove the directory path from a filename:
basename /home/user/myfile.txt
Output:
myfile.txt
To generate a filename for a temporary file:
tempfile=$(basename $(mktemp).tmp)
The variable tempfile will now contain the filename of a temporary file in the current directory.
With gencmd
gencmd given a path like this /dir1/dir2/filename.txt, extract only filename
- basename /dir1/dir2/filename.txt
gencmd given path /dir1/dir2/filename.txt.gz, extract only filename without extensions
- basename /dir1/dir2/filename.txt.gz
- basename -s .gz /dir1/dir2/filename.txt.gz
- basename /dir1/dir2/filename.txt.gz | cut -d ‘.’ -f 1
- basename /dir1/dir2/filename.txt.gz | cut -d. -f1
Conclusion
basename
extracts filenames from paths. It is useful for a variety of tasks, such as parsing URLs, removing directory paths from filenames, and generating filenames for temporary files.